package com.sean.community.comtroller;

import com.sean.community.entity.DiscussPost;
import com.sean.community.entity.Page;
import com.sean.community.service.ElasticsearchService;
import com.sean.community.service.LikeService;
import com.sean.community.service.UserService;
import com.sean.community.util.CommunityConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class SearchController implements CommunityConstant {
    private ElasticsearchService elasticsearchService;
    private UserService userService;
    private LikeService likeService;

    @Autowired
    public void setElasticsearchService(ElasticsearchService elasticsearchService) {
        this.elasticsearchService = elasticsearchService;
    }

    @Autowired
    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    @Autowired
    public void setLikeService(LikeService likeService) {
        this.likeService = likeService;
    }

    @RequestMapping(path = "/search", method = RequestMethod.GET)
    public String search(String keyword, Page page, Model model) throws IOException {
        // 搜索帖子
        Map<String, Object> searchResult = elasticsearchService.searchDiscussPost(keyword, page.getCurrent() - 1, page.getLimit());
        List<DiscussPost> discussPosts = (List<DiscussPost>) searchResult.get("searchResultList");
        // 结果视图
        List<Map<String, Object>> resultVo = new ArrayList<>();
        if(discussPosts != null){
            for(DiscussPost post : discussPosts){
                Map<String, Object> map = new HashMap<>();
                // 帖子
                map.put("discussPost", post);
                // 作者
                map.put("discussPostAuthor", userService.findUserById(post.getUserId()));
                // 点赞数
                map.put("likeCount", likeService.findEntityLikeCount(ENTITY_TYPE_DISCUSS_POST, post.getId()));
                // 添加到结果 Vo
                resultVo.add(map);
            }
        }
        model.addAllAttributes(new ModelMap("resultVo", resultVo));
        model.addAllAttributes(new ModelMap("keyword", keyword));
        // 设置分页
        page.setPath("/search?keyword=" + keyword);
        page.setRows(discussPosts == null ? 0 : (int)searchResult.get("searchResultCount"));
        return "/site/search";
    }
}
